/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
import React, { useState } from 'react';
import { connect } from 'dva';
import { Button, Col, Form, Input, message, Row, DatePicker } from 'antd';
import StandardTable from '@/components/StandardTable';
import moment from 'moment';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

const rangePcikerDefailtValue = {
  start: moment()
    .startOf('day')
    .subtract(1, 'days'),
  end: moment()
    .endOf('day')
    .subtract(1, 'days'),
};

const DispatStatisticsList = props => {
  const { form, dispatch, loading, statisticsList = {}, onChangeMode, defaultFormValue } = props;
  const { getFieldDecorator, validateFields } = form;
  const [selectRows, setSelectRows] = useState([]);
  const [outOfRange, setOutOfRange] = useState(false);
  const { list = [] } = statisticsList;
  const fotmatFormValue = then => {
    validateFields((error, values) => {
      if (error) return;
      const { date, search } = values;
      dispatch({
        type: 'dispatStatistics/save',
        payload: {
          defaultFormValue: values,
        },
      });
      const params = {
        search,
        start_time: moment(date[0]).format('YYYY-MM-DD'),
        end_time: moment(date[1]).format('YYYY-MM-DD'),
      };
      then(params);
    });
  };

  const onSubmit = pageOptions => {
    const { current, pageSize = 20 } = pageOptions;
    fotmatFormValue(values => {
      dispatch({
        type: 'dispatStatistics/getStatisticsList',
        payload: {
          ...values,
          page: current || 1,
          pageSize,
        },
      });
    });
  };
  form.reload = () => onSubmit(statisticsList.pagination || {});
  const onGrantDispat = dataList => {
    const paramsList = Array.isArray(dataList) ? dataList : selectRows;
    const formatList = paramsList
      .filter(item => item.status !== '已发放')
      .map(item => item.operator_kb_code);
    fotmatFormValue(({ start_time, end_time }) => {
      dispatch({
        type: 'dispatStatistics/onGrantDispat',
        payload: {
          courier_nos: formatList.toString(),
          start_time,
          end_time,
        },
      }).then(() => {
        setSelectRows([]);
        form.reload();
      });
    });
  };

  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      align: 'center',
      render: () => {
        const dates = defaultFormValue.date;
        const section = moment(dates[1]).diff(moment(dates[0]), 'days');
        if (section) {
          return `${moment(dates[0]).format('YYYY-MM-DD')} - ${moment(dates[1]).format(
            'YYYY-MM-DD',
          )}`;
        }
        return moment(dates[0]).format('YYYY-MM-DD');
      },
    },
    {
      title: '业务员',
      dataIndex: 'courier_name',
      key: 'courier_name',
      align: 'center',
      render: (text, record) => `${record.courier_name} ${record.courier_phone}`,
    },
    {
      title: '派件量',
      dataIndex: 'count',
      align: 'center',
    },
    {
      title: '派费',
      dataIndex: 'totalPrice',
      align: 'center',
    },
    {
      title: '是否发放',
      dataIndex: 'status',
      align: 'center',
    },
    {
      title: '操作',
      align: 'left',
      render: (_, record) => (
        <>
          <a onClick={onChangeMode.bind(null, record)}> 查看详情 </a>
          {record.status !== '已发放' && (
            <a onClick={onGrantDispat.bind(null, [record])} style={{ paddingLeft: 10 }}>
              发放
            </a>
          )}
        </>
      ),
    },
  ];

  const disabledDate = current =>
    current &&
    current >
      moment()
        .endOf('day')
        .subtract(1, 'days');

  const onRangePickerChange = dates => {
    const section = moment(dates[1]).diff(moment(dates[0]), 'days');
    if (section > 30) {
      message.warn('所选日期区间最大不得超过31天！');
      setOutOfRange(true);
    } else {
      setOutOfRange(false);
    }
  };
  const rangePickerOnBlur = () => {
    if (outOfRange) {
      form.setFieldsValue({
        date: [rangePcikerDefailtValue.end, rangePcikerDefailtValue.start],
      });
    }
  };

  const onExport = (data = {}) => {
    let params = {};
    fotmatFormValue(values => {
      params = values;
    });
    params.page = statisticsList.pagination.current || 1;

    dispatch({
      type: 'dispatStatistics/getStatisticsList',
      payload: {
        ...params,
        ...data,
      },
    });
  };

  return (
    <>
      <Form layout="inline" style={{ marginBottom: 24 }}>
        <FormItem label="公司站点">
          {getFieldDecorator('date', {
            initialValue: defaultFormValue.date || [
              moment(rangePcikerDefailtValue.start),
              moment(rangePcikerDefailtValue.end),
            ],
          })(
            <RangePicker
              style={{ width: '280px' }}
              placeholder={['开始日期', '结束日期']}
              disabledDate={disabledDate}
              onChange={onRangePickerChange}
              onBlur={rangePickerOnBlur}
            />,
          )}
        </FormItem>
        <FormItem label="业务员">
          {getFieldDecorator('search', {
            initialValue: defaultFormValue.search || '',
          })(
            <Input allowClear style={{ width: 250 }} placeholder="请输入业务员姓名或手机号搜索" />,
          )}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={onSubmit}>
            查询
          </Button>
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon="download"
            onClick={() => onExport({ is_export: '1' })}
            disabled={list.length === 0}
          >
            导出明细
          </Button>
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon="download"
            onClick={() => onExport({ is_export_all: '1' })}
            disabled={list.length === 0}
          >
            导出全部明细
          </Button>
        </FormItem>
      </Form>
      <StandardTable
        selectedRows={selectRows}
        onSelectRow={setSelectRows}
        rowKey="id"
        loading={loading}
        data={statisticsList}
        columns={columns}
        scroll={{ x: 800 }}
        onChange={onSubmit}
      />
      <Row type="flex" gutter={[20, 20]} style={{ margin: 0 }}>
        <Col>
          <Button
            onClick={onGrantDispat}
            disabled={!(selectRows.length && selectRows.some(item => item.status !== '已发放'))}
            type="primary"
          >
            批量发放
          </Button>
        </Col>
      </Row>
    </>
  );
};

export default connect(({ loading, dispatStatistics }) => ({
  loading: loading.effects['dispatStatistics/getStatisticsList'],
  dispatStatistics,
  statisticsList: dispatStatistics.statisticsList || [],
  defaultFormValue: dispatStatistics.defaultFormValue || {}, // form值，从详情返回后，保留当前搜索值
}))(React.memo(Form.create()(DispatStatisticsList)));
